﻿Namespace Localization
    <System.Windows.Markup.MarkupExtensionReturnType(GetType(System.Windows.Media.Imaging.BitmapSource))> _
    Public Class BitmapSourceExtension
        Inherits ResourceExtension

        Public Sub New()
            MyBase.New()
        End Sub

        Public Sub New(ByVal key As String)
            MyBase.New(key)
        End Sub

        Private Shared _NoImage As BitmapSource
        Public Shared ReadOnly Property NoImage As BitmapSource
            Get
                If _NoImage Is Nothing Then
                    _NoImage = New BitmapImage(New Uri("pack://application:,,,/WPFGlue;component/Localization/NoImage.png", UriKind.Absolute))
                End If
                Return _NoImage
            End Get
        End Property

        Public Overrides Function ProvideValue(ByVal serviceProvider As System.IServiceProvider) As Object
            Dim result As BitmapSource = NoImage
            If ResourceManager IsNot Nothing Then
                Dim data As System.Drawing.Bitmap = TryCast(ResourceManager.GetObject(Key), System.Drawing.Bitmap)
                If data IsNot Nothing Then
                    Dim sourceRect = New Int32Rect(0, 0, data.Width, data.Height)
                    result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(data.GetHbitmap, Nothing, sourceRect, BitmapSizeOptions.FromEmptyOptions)
                End If
            End If
            Return result
        End Function
    End Class
End Namespace
